import os


from config import CONFIG
from utils.chat_util import generate_chart, generate_pdf, send_email
from utils.logger_util import logger


def create_html_template(chart_base64):
    """创建HTML模板"""
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: "Microsoft YaHei"; }}
            .chart-container {{ text-align: center; margin: 30px 0; }}
            img {{ max-width: 80%; height: auto; }}
        </style>
    </head>
    <body>
        <h1 style="text-align:center;">数据分析报告</h1>

        <div class="chart-container">
            <h2>数据图表</h2>
            <img src="data:image/png;base64,{chart_base64}" alt="图表">
        </div>

        <div class="content">
            <h3>分析结论</h3>
            <p>这是自动生成的数据分析报告，包含可视化图表和详细说明。</p>
        </div>
    </body>
    </html>
    """


async def generate_and_send_report(data:dict):
    try:
        # 1. 生成图表数据

        chart_base64 = generate_chart(data.get('df'), x_label=data.get('x_label'),
                                      y_label=data.get('y_label'), title=data.get('title'))

        if not chart_base64:
            raise Exception("图表生成失败")

        # 2. 生成HTML内容
        html_content = create_html_template(chart_base64)

        # 3. 生成PDF文件
        pdf_path = os.path.join(CONFIG['pdf']['temp_dir'], "report.pdf")
        pdf_result = generate_pdf(html_content, pdf_path)

        if not pdf_result:
            raise Exception("PDF生成失败")

        # 4. 发送邮件
        recipients = ["65900370@qq.com"]
        subject = "数据分析报告 - 2025年6月"

        email_sent = send_email(
            subject=subject,
            recipients=recipients,
            html_content=html_content,
            attachments=[pdf_path]
        )

        if not email_sent:
            raise Exception("邮件发送失败")

        return {"status": "success", "message": "报告生成并发送成功"}

    except Exception as e:
        logger.error(f"处理报告失败: {str(e)}")
        return {"status":1}